summaryrefslogtreecommitdiff
path: root/app/api/rfq-attachments/[id]/route.ts
blob: df99c1ad679062595bcbef37fc26e3743b26e11e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import db from "@/db/db";
import { eq } from "drizzle-orm";
import { rfqLastAttachments, rfqLastAttachmentRevisions } from "@/db/schema";
import { deleteFile } from "@/lib/file-storage";

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: "인증이 필요합니다" },
        { status: 401 }
      );
    }

    const attachmentId = parseInt(params.id);

    // 트랜잭션 시작
    const result = await db.transaction(async (tx) => {
      // 1. 첨부파일 정보 조회
      const [attachment] = await tx
        .select()
        .from(rfqLastAttachments)
        .where(eq(rfqLastAttachments.id, attachmentId));
      
      if (!attachment) {
        throw new Error("첨부파일을 찾을 수 없습니다");
      }
      
      // 2. 모든 리비전 조회
      const revisions = await tx
        .select()
        .from(rfqLastAttachmentRevisions)
        .where(eq(rfqLastAttachmentRevisions.attachmentId, attachmentId));
      
      // 3. 모든 리비전 파일 삭제 (공용 삭제 함수 사용)
      for (const revision of revisions) {
        if (revision.filePath) {
          await deleteFile(revision.filePath);
        }
      }
      
      // 4. 리비전 레코드 삭제
      await tx
        .delete(rfqLastAttachmentRevisions)
        .where(eq(rfqLastAttachmentRevisions.attachmentId, attachmentId));
      
      // 5. 첨부파일 레코드 삭제
      await tx
        .delete(rfqLastAttachments)
        .where(eq(rfqLastAttachments.id, attachmentId));
      
      return attachment;
    });

    return NextResponse.json({
      success: true,
      message: "파일이 삭제되었습니다",
      data: result,
    });
    
  } catch (error) {
    console.error("Delete attachment error:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: error instanceof Error ? error.message : "파일 삭제 실패" 
      },
      { status: 500 }
    );
  }
}